
package com.oly.cms.web.config;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.oly.cms.general.service.taglib.WebTag;


/**错误页面视图 */
@Component
public class PageErrorViewResolver implements ErrorViewResolver {

    @Autowired
    private WebTag webTag;

    /**
     * 解析错误视图。
     * 根据HTTP状态码和请求信息，选择合适的错误页面并返回ModelAndView对象。
     * 
     * @param request HttpServletRequest对象，代表客户端的请求。
     * @param status  HttpStatus对象，表示HTTP响应的状态码。
     * @param model   包含请求中模型数据的Map。
     * @return ModelAndView对象，包含错误页面的信息和模型数据。
     */
    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        ModelAndView modelAndView = new ModelAndView();
        String path = model.get("path").toString();
        String themeName = "default";
        String[] sp = path.split("/");
        // 截取主题名 静态资源
        if (path.startsWith("/static") && sp.length > 2) {
            themeName = sp[2];
            // 非静态资源请求
        } else if (sp.length > 1) {
            themeName = sp[1];
        }
        // 判断主题是否存在
        if (!webTag.mapTheme().containsKey(themeName)) {
            themeName = "default";
        }
        modelAndView.addAllObjects(model);
        modelAndView.addObject("themeName", themeName);
        return getModelAndView(modelAndView, String.valueOf(status.value()), themeName);
    }

    private ModelAndView getModelAndView(ModelAndView modelAndView, String errorCode, String themeName) {
        if ("404".equals(errorCode)) {
            modelAndView.setViewName("/" + themeName + "/pages/error/404");
        } else if ("403".equals(errorCode)) {
            modelAndView.setViewName("/" + themeName + "/pages/error/403");
        } else if ("500".equals(errorCode)) {
            modelAndView.setViewName("/" + themeName + "/pages/error/500");
        } else {
            modelAndView.setViewName("/" + themeName + "/pages/error/404");
        }
        return modelAndView;
    }

}